package com.hgvip.controller;

import com.hgvip.common.entity.ResponseData;
import com.hgvip.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by arnold.zhu on 2017/8/2.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private MongoOperations mongoTemplate;

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseData saveUser() {
        mongoTemplate.save(new Users(1, "didi"));
        mongoTemplate.save(new Users(2, "mama"));
        mongoTemplate.save(new Users(3, "kaka"));
        List<Users> users = mongoTemplate.findAll(Users.class);
        return new ResponseData(200, "保存成功!", users);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseData getUsers() {
        List<Users> users = mongoTemplate.findAll(Users.class);
        return new ResponseData(200, "查询成功!", users);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseData updateUser(@PathVariable int id) {
        mongoTemplate.updateFirst(new Query(Criteria.where("userId").is(id)),
                Update.update("name", "hello world"), Users.class);
        return new ResponseData(200, "更新成功!");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseData deleteUser(@PathVariable int id) {
        mongoTemplate.remove(new Query(Criteria.where("userId").is(id)),
                Users.class);
        return new ResponseData(200, "删除成功!");
    }

}
